package com.xing.yunji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xing.yunji.common.ErrorCode;
import com.xing.yunji.constant.UserConstant;
import com.xing.yunji.exception.BusinessException;
import com.xing.yunji.mapper.UserMapper;
import com.xing.yunji.model.domain.User;
import com.xing.yunji.service.UserService;
import com.xing.yunji.utils.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.xing.yunji.constant.UserConstant.ADMIN_ROLE;
import static com.xing.yunji.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务实现类
 *
 * @author xing
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2023-03-08 20:01:56
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 盐值：混淆密码
     */
    private static final String SALT = "xing";


    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //1. 校验
        // 非空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        //长度
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度不能低于4位");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不能低于8位");
        }
        //账户不能包含特殊字符
        String pattern = ".*[*?!&￥$%^#,./@\";:><\\]\\[}{\\-=+_\\\\|》《。，、？’‘“”~`）].*$";
        if (Pattern.matches(pattern, userAccount)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号不能包含特殊字符");
        }
        //密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码和校验密码相同");
        }
        //账户不能重复 (查询了数据库，这个校验应该放到最后校验)
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("userAccount", userAccount);
        long count = this.count(qw);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已注册");
        }
        //2.加密
        String md5Password = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(md5Password);
        boolean result = this.save(user);//保存user成功后，会把id塞给user
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_EXCEPTION, "注册失败");
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1. 校验
        // 非空
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        //长度
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度过短");
        }
        //账户不能包含特殊字符
        String pattern = ".*[*?!&￥$%^#,./@\";:><\\]\\[}{\\-=+_\\\\|》《。，、？’‘“”~`）].*$";
        if (Pattern.matches(pattern, userAccount)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号不能包含特殊字符");
        }
        //2.加密
        String md5Password = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //查询用户是否存在
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("userAccount", userAccount).eq("userPassword", md5Password);
        User user = userMapper.selectOne(qw);
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码不正确");
        }
        //3.用户脱敏
        User safetyUser = getSaftyUser(user);
        //4.记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param user
     * @return
     */
    @Override
    public User getSaftyUser(User user) {
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setTags(user.getTags());
        return safetyUser;
    }

    /**
     * 根据标签列表，查询用户列表（内存版）
     * 方式二：查询所有用户，在内存中过滤出包含要查询的标签的用户
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagNameList, HttpServletRequest request) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = getLoginUser(request);
        //查询所有用户信息
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>()
                .isNotNull(User::getTags).notIn(User::getId, loginUser.getId()));
        Gson gson = new Gson();
        //并行流 parallelStream,存在线程安全问题，尽量避免对线程不安全的集合使用
        //占用系统计算资源，数据处理顺序不一致
        //线程切换和同步开销可能会超过并行处理的好处
        return userList.stream().filter(user -> {
            String tagsStr = user.getTags();//["java","c++","python"]
            Set<String> tagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {}.getType());//标签不能重复
            tagNameSet = Optional.ofNullable(tagNameSet).orElse(new HashSet<>());//java8 新特性，避免if else
            for (String tagName : tagNameList) {
                if (!tagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSaftyUser).collect(Collectors.toList());
    }

    @Override
    public int updateUser(User user, User loginUser) {
        Long userId = user.getId();
        if (userId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"要更新的用户id非法");
        }
        if(!isAdmin(loginUser)&& !loginUser.getId().equals(userId)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"非管理员不能修改其他用户信息");
        }
        User oldUser = userMapper.selectById(userId);
        if (oldUser==null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"要更新的用户不存在或已删除");
        }
        return userMapper.updateById(user);
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN,"用户未登录");
        }
        Long id = user.getId();
        //TODO 校验用户是否合法
        //查数据库，因为用户信息可能发生变化
        User currentUser = this.getById(id);
        if(currentUser==null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"当前用户已被删除！");
        }
        User saftyUser = this.getSaftyUser(currentUser);
        return saftyUser;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User loginUser = (User) userObj;
        return loginUser != null && loginUser.getUserRole() == ADMIN_ROLE;
    }

    @Override
    public List<User> matchUsers(long num, User loginUser) {
        //yunji:user:match:for:1
        String redisKey = UserConstant.USER_MATCH_KEY + loginUser.getId();
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        // 如果有缓存，直接读缓存
        Set<ZSetOperations.TypedTuple<Object>> set = zSetOperations.rangeByScoreWithScores(redisKey, 0, Integer.MAX_VALUE);
        if (CollectionUtils.isEmpty(set)){
            // 无缓存，查数据库
            // 查出所有用户 select （id tags） not null 加快查询效率
            long loginUserId = loginUser.getId();
            List<User> userList = this.list(new LambdaQueryWrapper<User>()
                    .select(User::getId, User::getTags)
                    .isNotNull(User::getTags).notIn(User::getId, loginUserId)
                    .last("limit "+num));
            // 获取标签列表 （当前用户tagList，其他用户的tagList）
            String loginUserTagsStr = loginUser.getTags();
            Gson gson = new Gson();
            List<String> loginUserTagList = gson.fromJson(loginUserTagsStr, new TypeToken<List<String>>() {
            }.getType());
//            System.out.println(loginUserTagList);//[男, java, c++, python, 大一]
            // 用zset保存
            for (int i = 0; i < userList.size(); i++) {
                User user = userList.get(i);
                List<String> userTagList = gson.fromJson(user.getTags(), new TypeToken<List<String>>() {
                }.getType());
                int distance = Algorithm.MinDistance(loginUserTagList, userTagList);
                System.out.println(userTagList+" : "+distance);
                //使用zset保存
                Long userId = user.getId();
                zSetOperations.add(redisKey,userId,distance);
                zSetOperations.getOperations().expire(redisKey,30, TimeUnit.MINUTES);
            }
        }
        // 根据key获取排行榜数据，然后获取userIdList，查询这些用户的信息
        ArrayList userIdList = new ArrayList();
        set = zSetOperations.rangeByScoreWithScores(redisKey, 0, Integer.MAX_VALUE);
        for (ZSetOperations.TypedTuple<Object> tuple : set) {
            userIdList.add(tuple.getValue());
        }
        List limitedUserIdList = (List) userIdList.stream().map(Object::toString).limit(num).collect(Collectors.toList());
        Object condition = limitedUserIdList.stream().collect(Collectors.joining(","));
        List<User> matchUserList = this.list(new LambdaQueryWrapper<User>()
                .in(User::getId, limitedUserIdList).last("order by field (id, "+condition+")"));
        matchUserList = matchUserList.stream().map(this::getSaftyUser).collect(Collectors.toList());
        return matchUserList;
    }

    /**
     * 根据标签列表，查询用户列表
     * 方式一：模糊查询：有几个标签就要模糊查询几次（SQL查询版）
     * select * FROM user WHERE isDelete=0 AND (tags LIKE ? AND tags LIKE ?)
     * @param tagNameList
     * @return
     */
    @Deprecated
    private List<User> searchUsersByTagsBySQL(List<String> tagNameList) {
        if(CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        for (String tagName : tagNameList) {
            queryWrapper.like("tags",tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList.stream().map(this::getSaftyUser).collect(Collectors.toList());

    }
}




